package com.alibaba.sample.kantiezi.dal.dao.ibatis;

import com.alibaba.sample.kantiezi.dal.dao.ProductDao;
import com.alibaba.sample.kantiezi.dal.dataobject.Product;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class IbatisProductDao extends SqlMapClientDaoSupport implements ProductDao {
    public List getProductListByCategoryId(String categoryId) {
        return getSqlMapClientTemplate().queryForList("getProductListByCategory", categoryId);
    }

    public Product getProductById(String productId) {
        return (Product) getSqlMapClientTemplate().queryForObject("getProduct", productId);
    }

    public List searchProductList(String keywords) {
        Object parameterObject = new ProductSearch(keywords);

        return getSqlMapClientTemplate().queryForList("searchProductList", parameterObject);
    }

    public void insertProduct(Product product) {
        getSqlMapClientTemplate().update("insertProduct", product);
    }

    /* Inner Classes */
    public static class ProductSearch {
        private List keywordList = new ArrayList();

        public ProductSearch(String keywords) {
            StringTokenizer splitter = new StringTokenizer(keywords, " ", false);

            while (splitter.hasMoreTokens()) {
                keywordList.add("%" + splitter.nextToken() + "%");
            }
        }

        public List getKeywordList() {
            return keywordList;
        }
    }
}
